package xyz.haijin.shiro.filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import xyz.haijin.shiro.entity.User;
import xyz.haijin.shiro.service.UserService;
import xyz.haijin.shiro.util.Constants;

import java.util.List;

/**
 * @author: haijin
 * @Date: 2022/12/28 14:08
 */
public class MyShiroRealm extends AuthorizingRealm {
    @Autowired(required = false)
    private UserService userService;

    //每次验证权限执行
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限验证");
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        List<Integer> roleIds = userService.getUserRoleIds(user.getId());
        if (roleIds != null && roleIds.size() > 0) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            for (Integer roleId : roleIds) {
                info.addRole(roleId.toString());
            }
            return info;
        }
        return null;
    }

    //登录执行
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String email = (String) authenticationToken.getPrincipal();
        User user = userService.getUserByEmail(email);
        if (user != null) {
            return new SimpleAuthenticationInfo(email, user.getPassword(), null, getName());
        }
        return null;
    }
}
